import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styled from 'styled-components';
import { Button, Card, Col, DatePicker, Row, Select } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import StandardTable from '@/components/StandardTable';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ProjectDiv = styled.div`
  .header-right {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }

  .header-left {
    display: flex;
  }

  .header-left-item {
    flex-grow: 1;
    flex-basis: 30%;
  }

  .header-left-item + .header-left-item {
    margin-left: 8px;
  }

  .nextplan-normal {
    //color: #32a24c;
  }

  .nextplan-danger {
    //color: #e64233;
  }

  .attachment-list {
    padding: 0;
  }

  .attachment-list-item {
    cursor: pointer;
    padding-top: 4px;
    padding-bottom: 4px;
  }

  .attachment-list-item:hover {
    color: #24a6f2;
  }
`;

@connect(({ projectjournal, user, loading }) => ({
  data: projectjournal.data,
  currentUser: user.currentUser,
  isLoading: loading.effects['projectjournal/listJournalsByPage'],
  // isCreating: loading.effects['projectjournal/create'],
  // isDeling: loading.effects['projectjournal/deleteJournalById'],
}))
class Project extends BaseComponent {
  constructor(props) {
    super(props);
    const now = moment(new Date());
    const start = now.set('date', 1).format('YYYY-MM-DD');
    const end = now.set('date', now.daysInMonth()).format('YYYY-MM-DD');
    this.state = {
      minRecordDatetime: start,
      maxRecordDatetime: end,
      // 所有的开发人员
      developers: [],
      // 所有的项目
      projects: [],
      // 被选中的日期
      selectDates: [moment(start), moment(end)],
      // 被选中的开发人员id
      developerId: [],
      // 被选中的项目编号
      projectId: [],
      // 被选中的rows
      selectedRowKeys: [],
    };
  }

  columns = [
    {
      title: '序号',
      key: 'col1',
      width: 100,
      render: (text, record, index) => {
        return <span>{index + 1}</span>;
      },
    },
    {
      title: '人员',
      width: 120,
      dataIndex: 'nickname',
    },
    {
      title: '项目',
      key: 'col2',
      // width: 150,
      dataIndex: 'project_name',
    },
    {
      title: '填写日期',
      // width: 150,
      dataIndex: 'record_datetime_text',
    },
    {
      title: '工作内容',
      key: 'col5',
      dataIndex: 'remarks',
      // fixed: 'right',
    },
    {
      title: '明日计划内容',
      key: 'col6',
      dataIndex: 'nextplan',
      // fixed: 'right',
      render: (text, record, index) => {
        const { nextplan } = record;
        if (nextplan) {
          return <span className={'nextplan-normal'}>{nextplan}</span>;
        } else {
          return <span className={'nextplan-danger'}>--</span>;
        }
      },
    },
    {
      title: '附件',
      key: 'col7',
      width: 300,
      fixed:'right',
      render: (text, record, index) => {
        const { attachments } = record;
        if (attachments) {
          return (
            <ul className={'attachment-list'}>
              {attachments.map((item, index) => {
                const { filePath } = item;
                return (
                  <li
                    className={'attachment-list-item'}
                    key={index}
                    onClick={() => {
                      if (filePath) {
                        window.open(filePath);
                      }
                    }}
                  >
                    {`${index + 1}.${item.fileName}`}
                  </li>
                );
              })}
            </ul>
          );
        } else {
          return <span>--</span>;
        }
      },
    },
  ];

  componentDidMount() {
    this.selectAllDevelopers();
    this.queryAllProjects();
    this.listJournalsByPage();
  }

  /**
   * 分页获取列表数据
   */
  listJournalsByPage = () => {
    this.listJournalsByPageBy({
      minRecordDatetime: this.state.minRecordDatetime,
      maxRecordDatetime: this.state.maxRecordDatetime,
      createBy: Array.isArray(this.state.developerId)
        ? this.state.developerId.join('|')
        : this.state.developerId,
      projectId: Array.isArray(this.state.projectId)
        ? this.state.projectId.join('|')
        : this.state.projectId,
    });
  };

  listJournalsByPageBy = params => {
    this.execHttp('projectjournal/listJournalsByPage', { currentPage: 1, pageSize: 10, ...params });
  };

  /**
   * 获取所有的项目列表
   */
  queryAllProjects = () => {
    this.execHttp('projectjournal/queryAllProjects', {}).then(resp => {
      const { success, data } = resp;
      if (success) {
        const { projects } = data;
        this.setState({
          projects: projects,
        });
      }
    });
  };

  /**
   * 获取所有的开发人员
   */
  selectAllDevelopers = () => {
    this.execHttp('projectjournal/selectAllDevelopers', {}).then(resp => {
      const { success, data } = resp;
      if (success) {
        const { developers } = data;
        this.setState({
          developers: developers,
        });
      }
    });
  };

  render() {
    const {
      developers,
      selectDates,
      developerId,
      selectedRowKeys,
      projects,
      projectId,
    } = this.state;
    return (
      <ProjectDiv>
        <Card bordered={true} title={'项目管理'}>
          <Row>
            <Col span={16}>
              <div className={'header-left'}>
                <RangePicker
                  className={'header-left-item'}
                  allowClear
                  value={selectDates}
                  onChange={this.handleRangePickerChange}
                />

                <Select
                  placeholder={'请选择开发人员'}
                  value={developerId}
                  allowClear
                  className={'header-left-item'}
                  // style={{ width: '200px', marginLeft: '8px' }}
                  onChange={this.handleDeveloperChange}
                >
                  {developers && developers.length > 0
                    ? developers.map((item, index) => {
                        return (
                          <Option key={index} value={item.id}>
                            {item.nickname}
                          </Option>
                        );
                      })
                    : null}
                </Select>

                <Select
                  placeholder={'请选择项目'}
                  className={'header-left-item'}
                  // style={{ width: '200px', marginLeft: '8px' }}
                  allowClear
                  value={projectId}
                  onChange={this.handleProjectChange}
                >
                  {projects && projects.length > 0
                    ? projects.map((item, index) => {
                        return (
                          <Option key={index} value={item.id}>
                            {item.projectName}
                          </Option>
                        );
                      })
                    : null}
                </Select>
              </div>
            </Col>
            <Col span={8}>
              <div className={'header-right'}>
                <Button style={{ marginLeft: '8px' }} onClick={this.handleResetClick}>
                  重置
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: '8px' }}
                  onClick={this.handleSearchClick}
                >
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Card>
        <Card bordered={true} style={{ marginTop: '16px' }}>
          <StandardTable
            data={this.props.data}
            hasSelection={false}
            selectedRows={selectedRowKeys}
            columns={this.columns}
            rowKey={'id'}
            loading={this.props.isLoading}
            onChange={this.handleTableChange}
            scroll={{ x: true }}
          />
        </Card>
      </ProjectDiv>
    );
  }

  handleRangePickerChange = dates => {
    if (dates && dates.length > 0) {
      this.setState(
        {
          minRecordDatetime: dates[0].format('YYYY-MM-DD'),
          maxRecordDatetime: dates[1].format('YYYY-MM-DD'),
          selectDates: dates,
        },
        () => {
          this.listJournalsByPage();
        }
      );
    } else {
      const now = moment(new Date());
      const start = now.set('date', 1).format('YYYY-MM-DD');
      const end = now.set('date', now.daysInMonth()).format('YYYY-MM-DD');
      this.setState(
        {
          minRecordDatetime: start,
          maxRecordDatetime: end,
          selectDates: dates,
        },
        () => {
          this.listJournalsByPage();
        }
      );
    }
  };

  handleProjectChange = value => {
    this.setState({ projectId: value }, () => {
      this.listJournalsByPage();
    });
  };

  handleDeveloperChange = value => {
    this.setState({ developerId: value }, () => {
      this.listJournalsByPage();
    });
  };

  handleResetClick = () => {
    const now = moment(new Date());
    const start = now.set('date', 1).format('YYYY-MM-DD');
    const end = now.set('date', now.daysInMonth()).format('YYYY-MM-DD');
    this.setState(
      {
        selectDates: null,
        minRecordDatetime: start,
        maxRecordDatetime: end,
        developerId: [],
        projectId: [],
      },
      () => {
        this.listJournalsByPage();
      }
    );
  };

  handleSearchClick = () => {
    this.listJournalsByPageBy({
      minRecordDatetime: this.state.minRecordDatetime,
      maxRecordDatetime: this.state.maxRecordDatetime,
      createBy: Array.isArray(this.state.developerId)
        ? this.state.developerId.join('|')
        : this.state.developerId,
      projectId: Array.isArray(this.state.projectId)
        ? this.state.projectId.join('|')
        : this.state.projectId,
    });
  };

  /**
   * table状态改变时调用
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      minRecordDatetime: this.state.minRecordDatetime,
      maxRecordDatetime: this.state.maxRecordDatetime,
      createBy: Array.isArray(this.state.developerId)
        ? this.state.developerId.join('|')
        : this.state.developerId,
      projectId: Array.isArray(this.state.projectId)
        ? this.state.projectId.join('|')
        : this.state.projectId,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.listJournalsByPageBy(params);
  };
}

export default Project;
